package com.iretailer.report.quartz.sendReqularly.protocol;

import com.iretailer.report.model.SendRegularly;
import com.iretailer.report.quartz.sendReqularly.model.FlowArray;
import com.iretailer.report.quartz.sendReqularly.model.ServerConfig;
import com.iretailer.report.quartz.sendReqularly.util.CommonUtil;
import com.iretailer.report.util.StringUtil;
import com.iretailer.report.util.TimeUtil;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Auther: xjw
 * @Date: 2019/8/1 0001 10:23
 * @Description:
 */
public class FtpProtocol {

    private String host;
    private int port;
    private String userName;
    private String password;

    public FtpProtocol(String host, int port, String userName, String password) {
        this.host = host;
        this.port = port;
        this.userName = userName;
        this.password = password;
    }

    public static boolean initAndSend(SendRegularly s, ServerConfig config, String fileName, byte[] message) throws Exception {
        FtpProtocol ftp = new FtpProtocol(config.getHost(), config.getPort(), config.getUserName(), config.getPassword());
        return ftp.upload(config.getDirectory(), config.getWorkMode(), fileName, message);
    }


    public boolean upload(String filePath, String workMode, String fileName, byte[] message) throws Exception {
        boolean result = false;
        InputStream is = null;

        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(host, port);
            int reply = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                boolean login = ftpClient.login(userName, password);
                if (!login) {
                    throw new Exception("Account password error");
                }
                boolean flag = ftpClient.changeWorkingDirectory(filePath);
                if (flag) {
                    // 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
                    ftpClient.setFileType(FTP.LOCAL_FILE_TYPE);
                    //主动模式还是 被动模式
                    if ("active".equals(workMode)) {
                        ftpClient.enterLocalActiveMode();
                    } else {
                        ftpClient.enterLocalPassiveMode();
                    }
                    is = new ByteArrayInputStream(message);
                    boolean store = ftpClient.storeFile(fileName, is);
                    if (store) {
                        result = true;
                    } else {
                        throw new RuntimeException("store file is fail");
                    }
                } else {
                    throw new RuntimeException(String.format("ftp server not have this path %s", filePath));
                }

            } else {
                throw new RuntimeException("ftp connect to host failed");
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (is != null) {
                is.close();
            }
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
        return result;
    }
}
